package com.aurora.oa.signin.view;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.aurora.oa.R;
import com.aurora.oa.application.MyApplication;
import com.aurora.oa.signin.presenter.SigninFragmentPresenter;
import com.aurora.oa.signin.presenter.SigninFragmentPresenterImpl;
import com.aurora.oa.utils.SharedPreferencesUtil;
import com.aurora.oa.utils.ToastUtil;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.model.LatLng;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2017/3/15 0015.
 */
public class SigninMainFragment  extends Fragment implements SigninFragmentView{


    TextView tv_address;
    TextView tv_current_date;
    TextView tv_current_time;
    TextView tv_depart;
    EditText et_work_plan;
    EditText et_custom;
    LinearLayout ll_sign;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();
    private MyLocationConfiguration.LocationMode mCurrentMode;
    BitmapDescriptor mCurrentMarker;
    private static final int accuracyCircleFillColor = 0xAAFFFF88;
    private static final int accuracyCircleStrokeColor = 0xAA00FF00;
    MapView mMapView;
    BaiduMap mBaiduMap;
    boolean isFirstLoc = true; // 是否首次定位
    View surrentView;
    SigninFragmentPresenter mPresenter;
    private String param;
    Activity mAct;
    BDLocation myLocationInfo;
    private TextView tv_sign_info;
    Handler handler = new Handler();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mAct = getActivity();
        // 布局及地图初始化
        if(surrentView==null){
            surrentView = inflater.inflate(R.layout.fragment_sign_main,container,false);
            mMapView = (MapView) surrentView.findViewById(R.id.bmapView);
            tv_address = (TextView)  surrentView.findViewById(R.id.tv_address);
            tv_current_date =(TextView)  surrentView.findViewById(R.id.tv_current_date);
            tv_current_time = (TextView)  surrentView.findViewById(R.id.tv_current_time);
            tv_sign_info = (TextView) surrentView.findViewById(R.id.tv_sign_info);
            tv_depart=(TextView)  surrentView.findViewById(R.id.tv_depart);
            ll_sign =(LinearLayout) surrentView.findViewById(R.id.ll_sign);
            et_work_plan = (EditText)surrentView.findViewById(R.id.et_work_plan);
            et_custom =(EditText)surrentView.findViewById(R.id.et_custom);
            mBaiduMap = mMapView.getMap();
            // 开启定位图层
            mBaiduMap.setMyLocationEnabled(true);
            // 定位初始化
            handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mLocClient = new LocationClient(mAct);
                    mLocClient.registerLocationListener(myListener);
                    LocationClientOption option = new LocationClientOption();
                    option.setOpenGps(true); // 打开gps
                    option.setCoorType("bd09ll"); // 设置坐标类型
                    option.setScanSpan(1000);
                    option.setIsNeedAddress(true);
                    mLocClient.setLocOption(option);
                    mLocClient.start();
                }
            },1000);
/*            option.setLocationMode(LocationMode.Hight_Accuracy);
            //可选，默认高精度，设置定位模式，高精度，低功耗，仅设备

            option.setCoorType("bd09ll");
            //可选，默认gcj02，设置返回的定位结果坐标系

            int span=1000;
            option.setScanSpan(span);
            //可选，默认0，即仅定位一次，设置发起定位请求的间隔需要大于等于1000ms才是有效的

            option.setIsNeedAddress(true);
            //可选，设置是否需要地址信息，默认不需要

            option.setOpenGps(true);
            //可选，默认false,设置是否使用gps

            option.setLocationNotify(true);
            //可选，默认false，设置是否当GPS有效时按照1S/1次频率输出GPS结果

            option.setIsNeedLocationDescribe(true);
            //可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”

            option.setIsNeedLocationPoiList(true);
            //可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到

            option.setIgnoreKillProcess(false);
            //可选，默认true，定位SDK内部是一个SERVICE，并放到了独立进程，设置是否在stop的时候杀死这个进程，默认不杀死

            option.SetIgnoreCacheException(false);
            //可选，默认false，设置是否收集CRASH信息，默认收集

            option.setEnableSimulateGps(false);
            //可选，默认false，设置是否需要过滤GPS仿真结果，默认需要*/

        }
        return surrentView;
    }


    public static SigninMainFragment newInstance(String param){
        SigninMainFragment signinFragment = new SigninMainFragment();
        Bundle bundle = new Bundle();
        bundle.putString("param",param);
        signinFragment.setArguments(bundle);
        return signinFragment;

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(savedInstanceState!=null){
            param = savedInstanceState.getString("param");
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mPresenter = new SigninFragmentPresenterImpl(this);
        initBaseUI();
    }

    private void initBaseUI() {
        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);//获取年份
        int month=cal.get(Calendar.MONTH)+1;//获取月份
        int day=cal.get(Calendar.DATE);//获取日
        tv_current_date.setText(year+"年"+month+"月"+day+"日");
        tv_depart.setText("所属部门："+MyApplication.getInstance().getLoginUser().getDepartment());
        ll_sign.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Map<String,String> signData = new HashMap<String, String>();
                if(myLocationInfo==null){
                    ToastUtil.show(mAct,"未获取到定位信息，稍后再试！");
                    return;
                }
                signData.put("longitude",myLocationInfo.getLongitude()+"");
                signData.put("latitude",myLocationInfo.getLatitude()+"");
                signData.put("address",myLocationInfo.getAddrStr());
                signData.put("visitobject",et_custom.getText().toString());
                signData.put("remark",et_work_plan.getText().toString());
                WifiManager wifiMgr = (WifiManager) mAct.getSystemService(Context.WIFI_SERVICE);
                int wifiState = wifiMgr.getWifiState();
                WifiInfo info = wifiMgr.getConnectionInfo();
                String wifiId = info != null ? info.getSSID() : "";
                signData.put("wifiName",wifiId);
                mPresenter.doSignin(signData);
            }
        });

        //如果保存有今日签到信息，提示已签到
        if(SharedPreferencesUtil.getString(mAct,SharedPreferencesUtil.SIGN_DATE).equals(tv_current_date.getText().toString())){
            tv_sign_info.setText("你今天已签到，工作愉快！");
            tv_sign_info.setTextColor(Color.parseColor(getString(R.color.orange)));
        }

    }

    @Override
    public void onSigninSuccess() {
        ToastUtil.show(mAct,"签到成功");
        //保存今日签到信息
        SharedPreferencesUtil.saveString(mAct,SharedPreferencesUtil.SIGN_DATE,tv_current_date.getText().toString());
        //提示已签到
        tv_sign_info.setText("你今天已签到，工作愉快！");
        tv_sign_info.setTextColor(Color.parseColor(getString(R.color.orange)));
    }

    @Override
    public void onSigninFail(String msg) {
        ToastUtil.show(mAct,"签到失败"+msg);
    }


    /**
     * 定位SDK监听函数
     */
    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            Calendar calendar=Calendar.getInstance();
            int hour =calendar.get(Calendar.HOUR_OF_DAY);
            int minute = calendar.get(Calendar.MINUTE);
            String shour = hour<10?"0"+hour:hour+"";
            String sminute =minute<10?"0"+minute:minute+"";
            tv_current_time.setText(shour+":"+sminute);
            if (location == null || mMapView == null) {
                return;
            }
            myLocationInfo = location;
            String address = location.getAddrStr();
            String city =location.getCity();
            String street =location.getStreet();
            if(address!=null){
                tv_address.setText(address);
            }
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);

            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    @Override
    public void onPause() {
        mMapView.onPause();
        super.onPause();
    }

    @Override
    public void onResume() {
        mMapView.onResume();
        super.onResume();
    }

    @Override
    public void onDestroy() {
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;
        super.onDestroy();
    }
}
